package com.elong.qadev.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.elong.qadev.entity.ConfigBrowser;
import com.elong.qadev.entity.DBLink;
import com.elong.qadev.entity.DBSql;
import com.elong.qadev.entity.User;
import com.elong.qadev.service.ConfigServiceI;
import com.elong.qadev.service.HttpCaseServiceI;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * @ClassName: DBConfigAction
 * @Description: TODO(数据库配置数据的增删改查)
 * @author kangchen
 * @date 2015年9月21日
 *
 */
@ParentPackage("all")
public class ConfigAction extends ActionSupport {
	Logger logger = Logger.getLogger(ConfigAction.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ArrayList<DBLink> dbLinks = new ArrayList<DBLink>();
	private ArrayList<DBSql> dbSqls = new ArrayList<DBSql>();
	private ArrayList<ConfigBrowser> browsers = new ArrayList<ConfigBrowser>();

	public ArrayList<ConfigBrowser> getBrowsers() {
		return browsers;
	}

	public void setBrowsers(ArrayList<ConfigBrowser> browsers) {
		this.browsers = browsers;
	}

	private DBLink dbLink;
	private DBSql dbSql;
	private ConfigBrowser browser;

	public ConfigBrowser getBrowser() {
		return browser;
	}

	public void setBrowser(ConfigBrowser browser) {
		this.browser = browser;
	}

	public DBLink getDbLink() {
		return dbLink;
	}

	public void setDbLink(DBLink dbLink) {
		this.dbLink = dbLink;
	}

	public DBSql getDbSql() {
		return dbSql;
	}

	public void setDbSql(DBSql dbSql) {
		this.dbSql = dbSql;
	}

	@Autowired
	private HttpCaseServiceI httpCaseService;
	@Autowired
	private ConfigServiceI configService;

	public ArrayList<DBLink> getDbLinks() {
		return dbLinks;
	}

	public void setDbLinks(ArrayList<DBLink> dbLinks) {
		this.dbLinks = dbLinks;
	}

	public ArrayList<DBSql> getDbSqls() {
		return dbSqls;
	}

	public void setDbSqls(ArrayList<DBSql> dbSqls) {
		this.dbSqls = dbSqls;
	}

	/**
	 * 
	 * @Title: getConfigInfo
	 * @Description: TODO(返回DB-SQL配置数据提供给struts展示)
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "getConfigInfo", results = { @Result(name = "success", location = "/config/dbConfig.jsp", type = "dispatcher") })
	public String getConfigInfo() {
		logger.info("获取DB配置信息");
		dbLinks = httpCaseService.getDBLinks();
		dbSqls = httpCaseService.getDBSqls();
		return "success";
	}

	@Action(value = "getBrowserConfig", results = { @Result(name = "success", location = "/config/browserConfig.jsp", type = "dispatcher") })
	public String getBrowserConfig() {
		logger.info("获取browser配置信息");
		browsers = configService.getConfigBrowsers();
		return "success";
	}

	/**
	 * 
	 * @Title: saveDBLink
	 * @Description: TODO(保存DB连接配置)
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "saveDBLink", results = { @Result(name = "success", location = "/config/getConfigInfo.jsp", type = "dispatcher") })
	public String saveDBLink() {
		User u = (User) ActionContext.getContext().getSession().get("user");
		dbLink.setConfiger(u.getName());
		dbLink.setCreateDate(new Date());
		logger.info("需要存入的dbLink是：" + dbLink.toString());
		if (httpCaseService.saveDBLink(dbLink)) {
			return "success";
		} else {
			return "success";
		}
	}

	/**
	 * 
	 * @Title: saveDBSql
	 * @Description: TODO(保存SQL数据配置)
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "saveDBSql", results = { @Result(name = "success", location = "/config/getConfigInfo.jsp", type = "dispatcher") })
	public String saveDBSql() {
		User u = (User) ActionContext.getContext().getSession().get("user");
		dbSql.setConfiger(u.getName());
		dbSql.setCreateDate(new Date());
		logger.info("需要存入的dbSql是：" + dbSql.toString());
		if (httpCaseService.saveDBSql(dbSql)) {
			return "success";
		} else {
			return "success";
		}
	}

	@Action(value = "saveConfigBrowser", results = { @Result(name = "success", location = "/config/getBrowserConfig.jsp", type = "dispatcher") })
	public String saveConfigBrowser() {
		User u = (User) ActionContext.getContext().getSession().get("user");
		browser.setConfiger(u.getName());
		browser.setCreateDate(new Date());
		logger.info("需要存入的browser是：" + browser.toString());
		if (configService.saveDBSql(browser)) {
			return "success";
		} else {
			return "success";
		}
	}

	/**
	 * 
	 * @Title: deleteDBLink
	 * @Description: TODO(删除DB连接)
	 * @param @return
	 * @param @throws Exception 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "deleteDBLink", results = { @Result(name = "success", location = "/config/getConfigInfo.jsp", type = "dispatcher") })
	public String deleteDBLink() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("UTF-8");
		String ids = new String(
				(request.getParameter("id")).getBytes("iso-8859-1"), "UTF-8");
		int id = Integer.parseInt(ids);
		logger.info("需要删除的dbLink-id是：" + id);
		if (httpCaseService.deleteDBLink(id)) {
			return "success";
		} else {
			return "success";
		}
	}

	/**
	 * 
	 * @Title: deleteDBSql
	 * @Description: TODO(删除SQL配置)
	 * @param @return
	 * @param @throws Exception 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "deleteDBSql", results = { @Result(name = "success", location = "/config/getConfigInfo.jsp", type = "dispatcher") })
	public String deleteDBSql() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("UTF-8");
		String ids = new String(
				(request.getParameter("id")).getBytes("iso-8859-1"), "UTF-8");
		int id = Integer.parseInt(ids);
		logger.info("需要删除的dbSql-id是：" + id);
		if (httpCaseService.deleteDBSql(id)) {
			return "success";
		} else {
			return "success";
		}
	}

	@Action(value = "deleteConfigBrowser", results = { @Result(name = "success", location = "/config/getBrowserConfig.jsp", type = "dispatcher") })
	public String deleteConfigBrowser() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("UTF-8");
		String ids = new String(
				(request.getParameter("id")).getBytes("iso-8859-1"), "UTF-8");
		int id = Integer.parseInt(ids);
		logger.info("需要删除的deleteConfigBrowser-id是：" + id);
		if (configService.deleteConfigBrowser(id)) {
			return "success";
		} else {
			return "success";
		}
	}

	@Action(value = "statusCheck")
	public void statusCheck() {

		browsers = configService.getConfigBrowsers();

		String msg = "";
		
		int temp = 0;
		for (int i = 0; i < browsers.size(); i++) {
			ConfigBrowser cb = browsers.get(i);
			if (cb == null) {
				continue;
			}
			String ip = cb.getIp();
			int port = Integer.parseInt(cb.getPort());
			try {
				Socket sc = new Socket(ip, port);
				logger.info("检测在线【" + browsers.get(i).toString() + "】");
				sc.close();
			} catch (Exception e) {
				logger.info("检测不在线【" + browsers.get(i).toString() + "】");
				if(temp==0){
					msg=cb.getId()+"";
					temp++;
				}else{
					msg += "," + cb.getId();					
				}
			}
		}
		
		logger.info("返回的需要停止的数据是："+msg);
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(msg);
		out.flush();
		out.close();
	}
}
